package com.hliushi.mq.base.producer;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * 发送异步消息
 *
 * @author llhuang10
 * @date 2021/8/11 16:04
 */
public class AsyncProducer {


    public static void main(String[] args) {
        // 1.创建消息生产者producer, 并指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        // 2.指定Nameserver地址
        producer.setNamesrvAddr("cvm-node01:9876;cvm-node02:9876");
        // 3.发送消息
        try {
            producer.start();
            for (int i = 0; i < 10; i++) {
                // 4.创建消息, 指定主题Topic, Tag和消费题
                Message message = new Message("base", "Tag2", ("hello world" + i).getBytes());
                /**
                 * 5.发送异步消息
                 * 异步发送消息给代理, 该方法立即返回, 发送完成后, 将执行sendCallback
                 */
                producer.send(message, new SendCallback() {

                    /**
                     * 发送成功回调函数
                     * @param sendResult 发送结果
                     */
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        System.out.println("发送结果 = " + sendResult);
                    }

                    /**
                     * 发送失败回调函数
                     * @param throwable
                     */
                    @Override
                    public void onException(Throwable throwable) {
                        System.out.println("发送异常 = " + throwable);
                    }
                });

                // 线程睡一秒
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (MQClientException | InterruptedException | RemotingException e) {
            e.printStackTrace();
        } finally {
            // 6.关闭生产者producer
            System.out.println("发送成功!");
            producer.shutdown();
        }
    }
}
